package com.taoym.voucher.common.utils;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.DES;
import com.taoym.voucher.common.response.ResponseStatusCode;
import org.springframework.util.ObjectUtils;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;

/**
 * @coder taoym
 * @datetime 2021/5/31 22:06
 * @desc 加密解密工具类
 */
public class SecureUtils {

    private static final String KEY;

    static {
        String profile = System.getProperty("user.dir") + "\\common\\src\\main\\resources\\profile.properties";
        Properties properties = new Properties();
        try {
            BufferedReader reader = new BufferedReader(new FileReader(profile));
            properties.load(reader);
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        KEY = properties.getProperty("SecureUtils.key");
    }

    /**
     * @coder taoym
     * @datetime 2021/5/31 22:10
     * @desc 加密
     */
    public static String encode(String secret) {

        if (ObjectUtils.isEmpty(secret)) {
            return "";
        }
        DES des = SecureUtil.des(KEY.getBytes());
        return des.encryptHex(des.encrypt(secret));
    }

    /**
     * @coder taoym
     * @datetime 2021/5/31 22:14
     * @desc 解密
     */
    public static String decrypt(String secret) {

        if (ObjectUtils.isEmpty(secret)) {
            return "";
        }
        DES des = SecureUtil.des(KEY.getBytes());

        try {
            return des.decryptStr(des.decrypt(secret));
        } catch (Exception e) {
            throw new ExceptionCore(ResponseStatusCode.KEY_IS_NOT_PI_PEI);
        }
    }
}
